// 引入核心类：
import QQMapWX from '@/libs/qqmap-wx-jssdk.min'
// 导入 async-validator 对参数进行验证
import Schema from 'async-validator'

import {
  reqAddAddress, reqAddressInfo,
  reqUpdateAddress
} from '../../../../../api/address'


Page({
  // 页面的初始数据
  data: {
    // 请求参数放在data下，方便进行绑定数据
    "name": "",//收货人
    "phone": "",//手机号码
    "provinceName": "",//省
    "provinceCode": "",//省编码
    "cityName": "",//市
    "cityCode": "",//市编码
    "districtName": "",//区
    "districtCode": "",//市编码
    "address": "",//详细地址
    "fullAddress": "",//完整地址
    "isDefault": false // 是否设置为默认地址，0不默认，1默认
  },

  // 保存收货地址
  async saveAddrssForm(event) {
    const { provinceName, cityName, districtName, address, isDefault } = this.data
    // 组织参数( 完整地址、是否设置为默认地址):
    // params: 最终需要发送的请求参数
    const params = {
      ...this.data,
      fullAddress: provinceName + cityName + districtName + address,
      isDefault: isDefault ? 1 : 0
    }

    // 对组织以后的参数进行验证，验证通过以后，需要调用新增的接口实现新增收货地址功能
    const { valid } = await this.validatorAddress(params)

    // 如果 valid 等于 false，说明验证失败，就不执行后续的逻辑
    if (!valid) return

    // const res = await reqAddAddress(params)

    // 如果 valid 等于 true，说明验证成功调用新增的接口实现新增收货地址功能
    const res = this.addressId
      ? await reqUpdateAddress(params)
      : await reqAddAddress(params)
    // console.log(res);

    // if (res.code === 200) {
    //   wx.navigateBack()
    //   // wx.toast({ title: '新增成功' })
    //   wx.toast({
    //     title: this.addressId ? '更新收货地址成功！' : '新增收货地址成功！'
    //   })
    // }

    if (res.code === 200) {
      // 返回到收货地址列表页面
      wx.navigateBack({
        success: () => {
          // 需要给用户进行提示
          wx.toast({
            title: this.addressId ? '更新收货地址成功！' : '新增收货地址成功！'
          })
        }
      })
    }



  },
  validatorAddress(params) {
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'
    const phoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'
    const rules = {
      name: [
        { required: true, message: '请输入收货人姓名' },
        { pattern: nameRegExp, message: '收货人姓名不合法' }
      ],
      phone: [
        { required: true, message: '请输入收货人手机号' },
        { pattern: phoneReg, message: '收货人手机号不合法' }
      ],
      provinceName: { required: true, message: '请选择收货人所在地区' },
      address: { required: true, message: '请输入详细地址' }
    }
    const validator = new Schema(rules)
    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        if (errors) {
          wx.toast({ title: errors[0].message })
          resolve({ valid: false })
        } else {
          resolve({ valid: true })
        }
      })
    })
  },
  onAddressChange(event) {
    const [provinceName, cityName, districtName] = event.detail.value
    const [provinceCode,
      cityCode,
      districtCode] = event.detail.code
    this.setData({
      provinceName, cityName, districtName, provinceCode,
      cityCode,
      districtCode
    })
  },
  async onLocation() {
    const { latitude, longitude, name } = await wx.chooseLocation()
    this.qqmapwx.reverseGeocoder({
      location: {
        longitude,
        latitude
      },
      success: (res) => {
        const { adcode, province, city, district } = res.result.ad_info
        const { street, street_number } = res.result.address_component
        const { standard_address } = res.result.formatted_addresses
        this.setData({
          provinceName: province,
          provinceCode: adcode.replace(adcode.substring(2, 6), '0000'),
          cityName: city,
          cityCode: adcode.replace(adcode.substring(4, 6), '00'),
          districtName: district,
          districtCode: district && adcode,
          address: street + street_number + name,
          fullAddress: standard_address + name
        })
      }
    })
  },
  async showAddressInfo(id) {
    if (!id) return
    this.addressId = id
    wx.setNavigationBarTitle({
      title: '更新收货地址'
    })
    const {data} = await reqAddressInfo(id)
    this.setData(data)
  },
  onLoad(options) {
    this.qqmapwx = new QQMapWX({
      key: 'NYMBZ-O4QLC-O7S2R-A3YPP-ERALS-N6BTY'
    })
    this.showAddressInfo(options.id)
  },
})
